'use strict';

const { Service } = require('egg');
const ModelName = 'Consume'
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','DESC']
      ],
      include: [
        {
          model: this.ctx.model.User,
        }
      ]
    });
  }

  // 所有列表
  async allList() {
    return this.ctx.model[ModelName].findAll({
      order:[
        // id 降序
        ['create_time','DESC']
      ],
      include: [
        {
          model: this.ctx.model.User,
        }
      ]
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
      include: [
        {
          model: this.ctx.model.User,
        }
      ]
    });
  }

  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    return this.ctx.model[ModelName].create(data);
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }

  /**
   * 每天定时消费未被消费的数据
   * @returns {Promise<void>}
   */
  async handle() {
    // 查出来所有用户
    const userList = await this.ctx.service.user.allList();
    // 查找token消耗配置
    const config = await this.ctx.model.Config.findAll()
    const findConsumeConfig = config.find(item => item.code === 'consume_token')
    const findConsumeSizeConfig = config.find(item => item.code === 'consume_size')
    if (!findConsumeConfig) return // 没有配置消费token
    const consume_token_value = parseInt(findConsumeConfig.value)
    const now = new Date()
    // 查未被消费的消息数据总数 截至现在之前
    const count = await this.ctx.model.Message.count({
        where: {
            status: 0,
            create_time: {
                [this.app.Sequelize.Op.lte]: now
            }
        }
    })
    if (count === 0) return
    const pageSize = findConsumeSizeConfig ? parseInt(findConsumeSizeConfig.value) ||  500 : 500
    let pageNums = Math.ceil(count / pageSize)
    // 分页处理
    while (pageNums > 0) {
        const pageData = await this.ctx.service.message.getPage({
            status: 0,
            create_time: {
                [this.app.Sequelize.Op.lte]: now
            }
        }, 1, pageSize);
        const rows = pageData.rows
        // 匹配用户的web_url是否存在rows中的answer字段
        for (let j = 0; j < userList.length; j++) {
            const user = userList[j]
            let consumeList = [] // 用户的消费记录
            let totalToken = 0 // 用户的总消费token数
            for (let i = 0; i < rows.length; i++) {
                const item = rows[i]
                // 查询一句话中包含web_url多少次
                const count = item.answer.split(user.web_url).length - 1
                if (count > 0) {
                    // 消耗token
                    const consume_token = count * consume_token_value
                    // 新增一条消费记录
                    consumeList.push({
                        user_id: user.id,
                        token: -consume_token,
                        content: user.web_url,
                        answer: item.answer,
                        consume_token: -consume_token_value,
                        count: count,
                        message_id: item.id
                    })
                    totalToken += consume_token
                }
                console.log('item.status',item.status)
                // 更新状态
                if (item.status === 0) {
                    await this.ctx.service.message.update(item.id, { status: 1 })
                    item.status = 1
                }
            }
            // 一次性扣更新账户token
            await this.ctx.model.User.update(
                { token: this.app.Sequelize.literal(`token - ${totalToken}`) },
                {
                    where: {
                        id: user.id
                    }
                }
            )
            // 批量插入消费记录
            await this.ctx.model.Consume.bulkCreate(consumeList)
        }

        pageNums--
    }
  }
}

module.exports = RouterService;
